<template>
  <memberSelect>
    <template #left>
      <TabsAside
        v-loading="categoryLoading"
        @active-tab-index="onActiveMenu"
        :tabs-list="categoryList"
    /></template>
    <template #content>
      <GoodsList :list="list" @handle-after-sale="onHandleAfterSale" @load="onHandleLoad">
        <template #tool>
          <ContentWrap class="!w-full border-none! mb-0!" :body-style="{ padding: 0 }">
            <el-row class="!w-full m-x-0!" justify="space-between" :gutter="5">
              <el-col :xs="24" :sm="24" :md="12" :lg="18" :xl="20">
                <Search
                  class="mb-10px"
                  placeholder-text="请输入商品名称\商品名称首字母\商品编码\条形码"
                />
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="6" :xl="4">
                <el-button type="primary" class="!w-100% mb-10px" @click="handleGoShoppingCart">
                  <Icon icon="ep:shopping-cart" :size="18" class="mr-5px" /> 已选资产
                  {{ cartNumber }}
                </el-button>
              </el-col>
            </el-row>
          </ContentWrap>
        </template>
      </GoodsList>
    </template>
  </memberSelect>
</template>
<script lang="ts" setup>
defineOptions({ name: 'ShopSales' })
import memberSelect from '../components/member/user/memberSelect.vue' //会员选择
import TabsAside from '@/views/shop/components/tabsAside/index.vue' //商品分类列表
import GoodsList from './components/GoodsList.vue' //卡项列表
import Search from '@/views/shop/components/search/index.vue' //搜索组件
import * as PayApi from '@/api/shop/trade/pay'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

/** 门店会员信息 */
import { useShopUserStoreWithOut } from '@/store/modules/shop/user'
const shopUserStore = useShopUserStoreWithOut()
const isSetUser = computed(() => {
  return shopUserStore.getIsSetUser
})
const shopUser = computed(() => {
  return shopUserStore.getUser
})

/** 购物车信息 */
import { useShopServiceWithOut } from '@/store/modules/shop/service'
const shopService = useShopServiceWithOut()
const cartNumber = computed(() => {
  return shopService.getCartNumber
}) //购物车数量
/**
 * 商品分类菜单
 */
import { ElMessageBox } from 'element-plus'
import _ from 'lodash'

const categoryLoading = ref(true) // 列表的加载中
const categoryList = ref<any[]>([]) // 列表的数据/** 查询列表 */
const getCategoryList = async () => {
  categoryLoading.value = true
  try {
    categoryList.value = [
      { id: '', name: '全部' },
      { id: 22, name: '寄存商品' },
      { id: 24, name: '订单商品' },
      { id: 20, name: '计次卡' },
      { id: 21, name: '计时卡' },
      { id: 22, name: '计时计次' }
    ]
  } finally {
    categoryLoading.value = false
  }
}
// 选中菜单
const activeMenu = ref(0)
const onActiveMenu = (index: number) => {
  activeMenu.value = index
  list.value = []
  queryParams.value.pageNo = 1

  getList()
}

/**
 * 商品列表
 */
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  userId: computed(() => {
    return shopUser.value.id
  }),
  skuType: ''
}) // 查询参数 (给组件传值)
const spuLoading = ref(true)
const list = ref<any>([])
const spuTotal = ref(0)
const loadStatus = ref('') //列表数据状态

/** 查询列表 */
const getList = async () => {
  if (!isSetUser.value) {
    message.error('请先选择会员')
  }
  spuLoading.value = true
  try {
    let unCategoryList = unref(categoryList.value)
    let unActiveMenu = unref(activeMenu.value)
    queryParams.value.skuType = unCategoryList[unActiveMenu].id

    console.log(queryParams.value)
    const data = await PayApi.getPayWalletPageCart(queryParams.value)
    list.value = _.concat(list.value, data.list)
    spuTotal.value = data.total
    loadStatus.value = list.value.length < spuTotal.value ? 'more' : 'noMore'
  } finally {
    spuLoading.value = false
  }
}
/** 分页查询列表 */
const onHandleLoad = () => {
  if (loadStatus.value === 'noMore') {
    return
  }
  queryParams.value.pageNo++
  getList()
}
// 选择商品

const onHandleAfterSale = (item) => {
  if (item.status == 0 || item.status == 2) {
    ElMessageBox.confirm('该卡项需要激活才能使用, 激活后不可撤销, 是否激活?', '激活卡项', {
      confirmButtonText: '确 认',
      cancelButtonText: '取 消'
    })
      .then(async () => {
        let params = {
          userId: shopUser.value.id,
          id: item.id
        }
        await PayApi.assetsActive(params)
        message.success('激活成功')
      })
      .catch(() => console.info('操作取消'))
  }
  if (item.status == -1) {
    ElMessageBox.confirm('该卡项需要支付欠款才能使用,是否支付欠款?', '提示', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel')
    })
      .then(async () => {})
      .catch(() => console.info('操作取消'))
  }
  if (item.status == 2) {
    message.error('该卡项已停卡')
    return
  }
  if (item.status == 3) {
    message.error('该卡项已用尽')
    return
  }
  if (item.status == 4) {
    message.error('该卡项已过期')
    return
  }
  if (item.status == 5) {
    message.error('该卡项已退款')
    return
  }
  onAddCart(item)
}
const onAddCart = (item) => {
  console.log(item)
  shopService.addCart(item)
} //加入购物车
const onHandleStop = async (item) => {
  const { value } = await ElMessageBox.prompt(
    '停卡只有1次机会，操作后不可撤销，是否需要停卡？',
    '提示',
    {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '停卡原因不能为空'
    }
  )

  let params = {
    userId: shopUser.value.id,
    id: item.id,
    pauseReason: value //停卡理由
  }
  // 发起取消
  await PayApi.assetsStop(params)
  message.success('停卡成功')
  // 刷新列表
  await getList()
}
/**去购物车列表 */
const router = useRouter() // 路由对象
const handleGoShoppingCart = () => {
  if (cartNumber.value > 0) {
    router.push({
      name: 'ShopPayCashierAfterSale',
      query: {
        returnUrl: encodeURIComponent('/shop/afterSale')
      }
    })
  } else {
    message.error('请先选择资产')
  }
} //去购物车

// 监听会员变化
watch(
  () => shopUser.value.id,
  () => {
    shopService.restSalesStateData()
    console.log(shopUser.value.id)
    if (shopUser.value.id > 0) {
      getList()
      shopService.getList() //获取购物车列表
      // shopService.getReplaceList()
    }
  }
)
onMounted(async () => {
  await getCategoryList()
  shopService.getList() //获取购物车列表

  onActiveMenu(0)
})
</script>
